package com.linewow.xhyy.nihaonew.activity;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.liangfeizc.flowlayout.FlowLayout;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseActivity;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.data.NewTopicData;
import com.linewow.xhyy.nihaonew.entity.tag.TagListInfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.linewow.xhyy.nihaonew.view.ColorfulTag;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.codefalling.recyclerviewswipedismiss.SwipeDismissRecyclerViewTouchListener;
import okhttp3.Call;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/9/27.
 */
public class NewCommitActivity extends BaseActivity {

    @Bind(R.id.commit_flow_layout)
    FlowLayout commitFlowLayout;
    @Bind(R.id.toolbar_find_title)
    TextView toolbarFindTitle;
    @Bind(R.id.toolbar_find_left)
    ImageView toolbarFindLeft;
    @Bind(R.id.toolbar_find_right)
    ImageView toolbarFindRight;
    @Bind(R.id.toolbar_find_right_tv)
    TextView toolbarFindRightTv;
    @Bind(R.id.commit_done_tag_recycler)
    RecyclerView commitDoneTagRecycler;
    @Bind(R.id.commit_done_tag_add)
    ImageView commitDoneTagAdd;
    @Bind(R.id.commit_hot_tag_tv)
    TextView commitHotTagTv;
    @Bind(R.id.toolbar_find_toolbar)
    Toolbar toolbarFindToolbar;
    @Bind(R.id.commit_done_tag_tv)
    TextView commitDoneTagTv;
    @Bind(R.id.commit_done_tag_icon)
    ImageView commitDoneTagIcon;
    @Bind(R.id.commit_done_tag_edit)
    EditText commitDoneTagEdit;
    private String TAG = "NewCommitActivity";
    private NewTopicData newTopicData;
    private List<TagListInfo> tagInfos;
    private NewCommitAdapter adapter;
    private Map<String,String>map;


    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_new_commit);
        ButterKnife.bind(this);
        toolbarFindRight.setVisibility(View.GONE);
        toolbarFindRightTv.setVisibility(View.VISIBLE);
        toolbarFindRightTv.setText(getString(R.string.widget_commit));
        toolbarFindTitle.setText(getString(R.string.title_new));
        toolbarFindLeft.setImageResource(R.mipmap.icon_back_white);
    }

    @Override
    public void initData() {
        super.initData();
        Bundle bundle = getIntent().getExtras();
        newTopicData = bundle.getParcelable("data");
        Log.e(TAG, "path1" + newTopicData.voicePath);
        Log.e(TAG, "图片path" + newTopicData.paths.get(0));
        Log.e(TAG, "图片path" + newTopicData.pathsJson);
        map=new HashMap<String,String>();
        map.put("desarr",newTopicData.pathsJson);
        if(newTopicData.voicePath!=null){
            map.put("audiotime",""+newTopicData.voiceLength);
        }
        if(newTopicData.website!=null){
            map.put("links",newTopicData.website);
        }
        if(newTopicData.location!=null){
            map.put("location",newTopicData.location);
        }
        if(newTopicData.subject!=null){
            map.put("subject",newTopicData.subject);
        }
    }

    @Override
    public void initList() {
        super.initList();
        NiHaoOkgo.tagListInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<BaseInfo<TagListInfo>, List<TagListInfo>>() {
                    @Override
                    public List<TagListInfo> call(BaseInfo<TagListInfo> tagListInfoBaseInfo) {
//                        dismissLoading();
                        return tagListInfoBaseInfo.data;
                    }
                })
                .flatMap(new Func1<List<TagListInfo>, Observable<TagListInfo>>() {
                    @Override
                    public Observable<TagListInfo> call(List<TagListInfo> tagListInfos) {
                        return Observable.from(tagListInfos);
                    }
                })
                .subscribe(new Action1<TagListInfo>() {
                    @Override
                    public void call(TagListInfo tagListInfo) {
                      Log.e(TAG,"消失掉dismiss");
                        ColorfulTag colorfulTag = new ColorfulTag(NewCommitActivity.this);
//                        colorfulTag.setHei(dp2px(15));
                        colorfulTag.setCustomTagsInfo(tagListInfo);
                        commitFlowLayout.addView(colorfulTag);
                        colorfulTag.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                TagListInfo info = (TagListInfo) view.getTag();
                                if(!tagInfos.contains(info)){
                                    tagInfos.add(info);
                                    adapter.notifyItemInserted(tagInfos.size());
                                }

                            }
                        });
                    }
                });
//        setContentList(list);
        tagInfos = new ArrayList<TagListInfo>();
        LinearLayoutManager manage = new LinearLayoutManager(NewCommitActivity.this);
        manage.setOrientation(LinearLayoutManager.HORIZONTAL);
        commitDoneTagRecycler.setItemAnimator(new DefaultItemAnimator());
        commitDoneTagRecycler.setLayoutManager(manage);
        SwipeDismissRecyclerViewTouchListener listener = new SwipeDismissRecyclerViewTouchListener.Builder(
                commitDoneTagRecycler,
                new SwipeDismissRecyclerViewTouchListener.DismissCallbacks() {
                    @Override
                    public boolean canDismiss(int position) {
                        tagInfos.remove(position);
                        adapter.notifyItemRemoved(position);
                        return true;
                    }

                    @Override
                    public void onDismiss(View view) {
                        // Do what you want when dismiss

                    }
                })
                .setIsVertical(false)
                .setItemTouchCallback(
                        new SwipeDismissRecyclerViewTouchListener.OnItemTouchCallBack() {
                            @Override
                            public void onTouch(int index) {
                                // Do what you want when item be touched
                            }
                        })
                .setItemClickCallback(new SwipeDismissRecyclerViewTouchListener.OnItemClickCallBack() {
                    @Override
                    public void onClick(int position) {
                        // Do what you want when item be clicked
                    }
                })
                .create();

        commitDoneTagRecycler.setOnTouchListener(listener);
        adapter=new NewCommitAdapter();
        commitDoneTagRecycler.setAdapter(adapter);

    }


//    public void setContentList(List<TagInfo> list) {
//
//        for (TagInfo temp : list) {
//            ColorfulTag colorfulTag = new ColorfulTag(NewCommitActivity.this);
//            colorfulTag.setHei(dp2px(15));
//            colorfulTag.setContent(temp);
//            commitFlowLayout.addView(colorfulTag);
//            colorfulTag.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    TagInfo info = (TagInfo) view.getTag();
//                    tagInfos.add(info);
//                    adapter.notifyItemInserted(tagInfos.size());
//                }
//            });
//        }
//    }

    public int dp2px(int dpValue) {
        return (int) (dpValue * getResources().getDisplayMetrics().density);
    }


    @OnClick({ R.id.toolbar_find_right_tv, R.id.commit_done_tag_add,R.id.toolbar_find_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_find_left:
                finish();
                break;
            case R.id.toolbar_find_right_tv:
                Log.e(TAG,"开始请求了3");
                checkData();


                break;
            case R.id.commit_done_tag_add:
                String string=new String(commitDoneTagEdit.getText().toString());

                for(TagListInfo temp:tagInfos){
                    if(temp.zhcn.equals(string)){
                        return;
                    }
                }
                TagListInfo tagInfo=new TagListInfo();
                tagInfo.setZhcn(string);
                tagInfos.add(tagInfo);
                adapter.notifyItemInserted(tagInfos.size()-1);
                commitDoneTagEdit.setText("");
                break;
        }
    }

    private void checkData() {
        if(tagInfos.size()==0){
            Toast.makeText(NewCommitActivity.this, "请添加标签", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.e(TAG,"要显示loading了");
        showLoading(NewCommitActivity.this.getString(R.string.message_committing));
        String tagJson=getTagJson();
        map.put("tags",tagJson);
        PostFormBuilder builder= OkHttpUtils.post();
        for(int i=0;i<newTopicData.paths.size();i++){
            builder.addFile("pic[]",newTopicData.paths.get(i),new File(newTopicData.paths.get(i)));
            Log.e(TAG,"遍历文件名pic[]tags"+newTopicData.paths.get(i));
        }
        if(newTopicData.voicePath!=null){
            builder.addFile("audio",newTopicData.voicePath,new File(newTopicData.voicePath));
        }

        builder.url("https://m.en1on1.com/api/api1.5/topic.php?ac=publish&token="+NiHaoApp.token)
                .params(map)
                .build()
                .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG,"打印失败了--->"+e.getMessage());
                        dismissLoading();
                        Observable.just("")
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribeOn(Schedulers.io())
                                .subscribe(new Observer<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        showCanDialog("发表失败了");
                                    }
                                });

                    }

                    @Override
                    public void onResponse(NiHaoEntity response, int id) {
                        Log.e(TAG,"得到response-->"+response);
                        dismissLoading();
                        if(response.status){
                            EventBus.getDefault().post(new MessageEvent(),"NewCommitActivity");
                            setResult(RESULT_OK);
                            showToast(NewCommitActivity.this.getString(R.string.intelligent_commit_success));
                            finish();
                        }
                    }
                });
    }

    public String getTagJson() {
        StringBuilder sb=new StringBuilder("[");
        for(int i=0;i<tagInfos.size();i++){
            if(i!=0){
                sb.append(",");
            }
            TagListInfo info=tagInfos.get(i);
            sb.append("\""+info.zhcn+"\"");
        }
        sb.append("]");
        return sb.toString();
    }


    public class NewCommitAdapter extends RecyclerView.Adapter<NewCommitHolder> {

        @Override
        public NewCommitHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(NewCommitActivity.this, R.layout.item_new_commit, null);
            return new NewCommitHolder(view);
        }

        @Override
        public void onBindViewHolder(NewCommitHolder holder, int position) {
            TagListInfo info = tagInfos.get(position);
            holder.colorfulTag.setCustomTagsInfo(info);
        }

        @Override
        public int getItemCount() {
            return tagInfos.size();
        }
    }

    public class NewCommitHolder extends RecyclerView.ViewHolder {
        public ColorfulTag colorfulTag;

        public NewCommitHolder(View itemView) {
            super(itemView);
            colorfulTag = (ColorfulTag) itemView.findViewById(R.id.item_commit_tag);
        }
    }
}
